package com.geeke.sys.utils;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.geeke.config.cache.GeekeRedisCache;
import com.geeke.sys.entity.Security;
import com.geeke.sys.service.SecurityService;


/**
 * 安全策略工具类
 * @author lys
 * @version 2023-8-29
 */
@Component("redisSecurityUtils")
public class RedisSecurityUtils {
	private static String CACHE_NAME = "security:login_failed";

	@Autowired
    private SecurityService securityService;
	
	@Autowired
	CacheManager cacheManager;
	
	/**
	 * 登录名是否应为超过次数被锁定
	 * @param loginName
	 */
	public boolean isLock(String loginName) {
		Cache cache = getCache();
		ValueWrapper value = cache.get(loginName );
		if(value == null) {
			return false;
		}
		Integer count = (Integer)value.get();

		// 安全策略配置
		Security security = securityService.get("1");

		return count.compareTo(security.getTryCount()) >= 0;
	}


	/**
	 * 锁定账户
	 * @param loginName
	 * @return 账户锁定时间（分钟），0标识未锁定
	 */
	public int lock(String loginName) {
		Cache cache = getCache();
		ValueWrapper value = cache.get(loginName);
		Integer count = value == null ? 1 :  (Integer)value.get() + 1;
		cache.put(loginName, count);

		// 安全策略配置 
		Security security = securityService.get("1");
		return count.compareTo(security.getTryCount()) >= 0 ?  security.getUnlockTime() : 0;

	}


	/**
	 * 解除账户锁定
	 * @param loginName
	 * @return
	 */
	public void unLock(String loginName) {
		Cache cache = getCache();
		cache.evict(loginName);
	}

	private Cache getCache() {
		GeekeRedisCache cache = (GeekeRedisCache)cacheManager.getCache(CACHE_NAME);

		// 安全策略配置 
		Security security = securityService.get("1");
		Duration duration = Duration.ofMinutes(security.getUnlockTime());
		cache.setTtl(duration);
		return cache;
	}
	
}
